package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetSalaryDataMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.WithoutObjMsg;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.CHScrollFieldView;
import com.lzx.iteam.widget.CHScrollView;
import com.lzx.iteam.widget.CHScrollWXYJView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2017年 01月 12日
 * Time: 下午4:31
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 五险一金表格 数据编辑页面
 */
public class SalaryWXYJFromActivity extends MyBaseActivity implements View.OnClickListener {

    @FindViewById(id = R.id.ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.tv_title_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.tv_title_right2)
    private TextView mTvEdit;
    @FindViewById(id = R.id.tv_title_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.ch_scroll_sub_class_excle)
    private CHScrollWXYJView mScrollViewWXYJ;
    @FindViewById(id = R.id.ll_sub_class_excle_date)
    private LinearLayout mLayoutWXYJ;
    @FindViewById(id = R.id.lv_sub_class_excle)
    private ListView mListView;

    //方便测试，直接写的public
    public HorizontalScrollView mTouchView;
    private List<CHScrollWXYJView> mHScrollViews = new ArrayList<>();
    private ArrayList<Map<String,Object>> mContentDatas = new ArrayList<>();
    private ArrayList<SalaryFieldBean> mMemberField = new ArrayList<>();
    private ArrayList<SalaryBaseBean> mDatas = new ArrayList<>();
    private SalaryRuleBean mRuleData;
    private MyAdapter mAdapter;


    private String mGroupId;
    private String[] mBaseTitle = {"养老基数","医疗基数","公积金基数"};
    private int mPositionX = -1;
    private int mPositionY = -1;

    private final int GET_SALARY_WXYJ = 30001;
    private final int SET_SALARY_WXYJ = 30002;
    private final int ACTICITY_REQUEST_WXYJ = 40000;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            waitDlgDismiss();
            if (msg.arg1 == 0){
                switch (msg.what){
                    case GET_SALARY_WXYJ:
                        mDatas = (ArrayList<SalaryBaseBean>) msg.obj;
                        setContentData();
                        break;
                    case SET_SALARY_WXYJ:
                        showShortToast("保存成功");
                        finish();
                        break;
                }
            }else{
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            }

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState,R.layout.salary_wxyj_form_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        mTvEdit.setOnClickListener(this);

    }

    @Override
    public void initData() {

        mTvTitle.setText("五险一金");
        mTvRight.setText("保存");
        mTvEdit.setText("缴纳比例");
        mTvEdit.setVisibility(View.VISIBLE);

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mRuleData = (SalaryRuleBean) intent.getSerializableExtra("salary_rule");


        setTitleData();
        getWXYJData();
    }


    /**
     * 设置标题数据
     */
    private void setTitleData(){

        mMemberField.clear();
        mMemberField.add(new SalaryFieldBean("养老基数"));
        mMemberField.add(new SalaryFieldBean("医疗基数"));
        mMemberField.add(new SalaryFieldBean("公积金基数"));

        mMemberField.add(new SalaryFieldBean("个人养老",StringUtil.floatFormat(mRuleData.getP_pension_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("个人医疗",StringUtil.floatFormat(mRuleData.getP_medical_pc() * 100) + "%" + "+" + StringUtil.floatFormat(mRuleData.getP_medical_count())));
        mMemberField.add(new SalaryFieldBean("个人失业",StringUtil.floatFormat(mRuleData.getP_unemployment_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("个人公积金",StringUtil.floatFormat(mRuleData.getP_provident_fund_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业养老",StringUtil.floatFormat(mRuleData.getC_pension_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业失业",StringUtil.floatFormat(mRuleData.getC_unemployment_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业工伤",StringUtil.floatFormat(mRuleData.getC_injury_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业生育",StringUtil.floatFormat(mRuleData.getC_birth_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业医疗",StringUtil.floatFormat(mRuleData.getC_medical_pc() * 100) + "%"));
        mMemberField.add(new SalaryFieldBean("企业公积金",StringUtil.floatFormat(mRuleData.getC_provident_fund_pc() * 100) + "%"));

        mLayoutWXYJ.removeAllViews();
        for (int i = 0; i < mMemberField.size(); i++) {
            SalaryFieldBean bean = mMemberField.get(i);
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(this, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
            tv.setGravity(Gravity.CENTER);
            tv.setLayoutParams(params);

            String tax = bean.getMoney();
            if (StringUtil.isEmpty(tax) || i < 3){
                tv.setText(bean.getName());
            }else{
                tv.setText(bean.getName() + "\n" +bean.getMoney());
            }
            tv.setTextColor(getResources().getColor(R.color.black));
            mLayoutWXYJ.addView(tv);
            View line = new View(mActivity);
            LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
            line.setLayoutParams(lineParams);
            line.setBackgroundResource(R.color.excle_line);
            mLayoutWXYJ.addView(line);
        }
        mHScrollViews.add(mScrollViewWXYJ);

    }

    /**
     * 设置列表数据
     */
    private void setContentData(){

        if (mDatas != null && mDatas.size() > 0) {
            mContentDatas.clear();
            for (int i = 0; i < mDatas.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                SalaryBaseBean bean = mDatas.get(i);
                map.put("user", bean);
                map.put("content", setWXYJData(bean));
                mContentDatas.add(map);
            }
            if (mAdapter == null){
                mAdapter = new MyAdapter();
                mListView.setAdapter(mAdapter);
            }else{
                mAdapter.notifyDataSetChanged();
            }

        } else {
            showShortToast("暂无考勤成员");
        }

    }

    /**
     * 设置 五险数据
     * @param bean
     * @return
     */
    private SalaryWXYJBean setWXYJData(SalaryBaseBean bean){

        SalaryWXYJBean content = new SalaryWXYJBean();
        /**
         * 养老基数  社保基数  公积金基数
         */
        float pension_base = bean.getPension_base();
        float medical_base = bean.getMedical_base();
        float provident_fund_base = bean.getProvident_fund_base();

        content.setPension_base(pension_base);
        content.setMedical_base(medical_base);
        content.setProvident_fund_base(provident_fund_base);

        /**
         * 个人五险一金
         */
        content.setP_pension_pc(pension_base*mRuleData.getP_pension_pc());
        if (medical_base == 0){
            content.setP_medical_pc(0);
        }else{
            content.setP_medical_pc(medical_base*mRuleData.getP_medical_pc() + mRuleData.getP_medical_count());
        }
        content.setP_provident_fund_pc(StringUtil.floatFormatToInt(provident_fund_base*mRuleData.getP_provident_fund_pc()));
        content.setP_unemployment_pc(pension_base*mRuleData.getP_unemployment_pc());

        /**
         * 公司五险一金
         */
        content.setC_pension_pc(pension_base*mRuleData.getC_pension_pc());
        content.setC_medical_pc(medical_base*mRuleData.getC_medical_pc());
        content.setC_provident_fund_pc(StringUtil.floatFormatToInt(provident_fund_base*mRuleData.getC_provident_fund_pc()));
        content.setC_unemployment_pc(pension_base*mRuleData.getC_unemployment_pc());
        content.setC_injury_pc(medical_base*mRuleData.getC_injury_pc());
        content.setC_birth_pc(medical_base*mRuleData.getC_birth_pc());

        return content;
    }

    /**
     * 刷新数据
     * @param number
     */
    private void upDateListData(String number){
        float f = 0;
        if (!StringUtil.isEmpty(number)){
            f = Float.parseFloat(number);
        }
        switch (mPositionX){
            case 0:
                mDatas.get(mPositionY).setPension_base(f);
                break;
            case 1:
                mDatas.get(mPositionY).setMedical_base(f);
                break;
            case 2:
                mDatas.get(mPositionY).setProvident_fund_base(f);
                break;
        }
        SalaryBaseBean bean = mDatas.get(mPositionY);
        mContentDatas.get(mPositionY).put("content",setWXYJData(bean));
        mAdapter.notifyDataSetChanged();

    }
    /**
     * 编辑框
     * @param title
     */
    public void showEditDialogMsg(String title,String content) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);

        mDialogUtil.salaryEditStyle(title,content,okText,cancelText,null,0);
        mDialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog, EditText ed) {
                String number = ed.getEditableText().toString().trim();
                upDateListData(number);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog, EditText ed) {
                lDialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_title_right:
                saveWXYIData();
                break;
            case R.id.tv_title_right2:
                Intent wxyj = new Intent(mActivity,SalaryWXYJActivity.class);
                wxyj.putExtra("group_id",mGroupId);
                wxyj.putExtra("salary_rule",mRuleData);
                startActivityForResult(wxyj,ACTICITY_REQUEST_WXYJ);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            mRuleData = (SalaryRuleBean) data.getSerializableExtra("salary_rule");
            mHScrollViews.clear();
            setTitleData();
            setContentData();
        }
    }

    public void onScrollChanged(int l, int t, int oldl, int oldt){

        for (CHScrollWXYJView scrollView : mHScrollViews) {
            if (mTouchView != scrollView)
                scrollView.smoothScrollTo(l, t);
        }

    }

    /**
     * 保存五险一金基数
     */
    private void saveWXYIData(){
        JSONArray members = new JSONArray();
        try {
            for (int i = 0; i < mDatas.size() ; i++) {
                SalaryBaseBean bean = mDatas.get(i);
                JSONObject obj = new JSONObject();
                obj.put("attendance_id",bean.get_id());
                obj.put("pension_base",bean.getPension_base());
                obj.put("medical_base",bean.getMedical_base());
                obj.put("provident_fund_base",bean.getProvident_fund_base());
                members.put(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setWXYJData(members.toString());
    }

    /**
     * 获取基数和五险一金
     */
    private void getWXYJData(){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetSalaryDataMsg msg = new GetSalaryDataMsg(mHandler.obtainMessage(GET_SALARY_WXYJ));
        msg.mApi = AsynHttpClient.API_SALARY_GET_WXYJ;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }

    /**
     * 获取基数和五险一金
     */
    private void setWXYJData(String members){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBERS, members));
        WithoutObjMsg msg = new WithoutObjMsg(mHandler.obtainMessage(SET_SALARY_WXYJ));
        msg.mApi = AsynHttpClient.API_SALARY_SET_WXYJ_BASE;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }


    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mContentDatas == null ? 0: mContentDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.salary_wxyj_item_layout,null);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_excle_item);
                holder.layoutScroll = (CHScrollWXYJView) convertView.findViewById(R.id.ch_scroll_excle_item);
                holder.layoutSub = (LinearLayout) convertView.findViewById(R.id.ll_excle_item);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            if (position%2 == 0){
                convertView.setBackgroundResource(R.color.excle_bg);
            }else{
                convertView.setBackgroundResource(R.color.white);
            }

            Map<String,Object> content = mContentDatas.get(position);
            SalaryBaseBean user = (SalaryBaseBean) content.get("user");
            holder.tvName.setText(user.getUser_name());

            SalaryWXYJBean bean = (SalaryWXYJBean) content.get("content");

            ArrayList<String> items = new ArrayList<>();
            items.add(bean.getPension_base() + "");
            items.add(bean.getMedical_base() + "");
            items.add(bean.getProvident_fund_base() + "");
            items.add(bean.getP_pension_pc() + "");
            items.add(bean.getP_medical_pc() + "");
            items.add(bean.getP_unemployment_pc() + "");
            items.add(bean.getP_provident_fund_pc() + "");
            items.add(bean.getC_pension_pc() + "");
            items.add(bean.getC_unemployment_pc() + "");
            items.add(bean.getC_injury_pc() + "");
            items.add(bean.getC_birth_pc() + "");
            items.add(bean.getC_medical_pc() + "");
            items.add(bean.getC_provident_fund_pc() + "");

            holder.layoutSub.removeAllViews();
            for (int i = 0; i < items.size(); i++) {
                TextView tv = new TextView(mContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
                tv.setGravity(Gravity.CENTER);
                tv.setLayoutParams(params);
                tv.setTextColor(getResources().getColor(R.color.black));
                tv.setText(StringUtil.floatFormat(items.get(i)));

                if (i < 3){
                    tv.setOnClickListener(new MyClickLinstener(i,position,true));
                }else{
                    tv.setOnClickListener(new MyClickLinstener(i,position,false));
                }

                holder.layoutSub.addView(tv);
                View line = new View(mActivity);
                LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
                line.setLayoutParams(lineParams);
                line.setBackgroundResource(R.color.excle_line);
                holder.layoutSub.addView(line);

            }

            if (!mHScrollViews.isEmpty()) {
                final int scrollX = mScrollViewWXYJ.getScrollX();
                //第一次满屏后，向下滑动，有一条数据在开始时未加入
                if (scrollX != 0) {
                    final ViewHolder finalHolder = holder;
                    mListView.post(new Runnable() {
                        @Override
                        public void run() {
                            //当listView刷新完成之后，把该条移动到最终位置
                            finalHolder.layoutScroll.scrollTo(scrollX, 0);
                        }
                    });
                }
            }
            mHScrollViews.add(holder.layoutScroll);
            return convertView;
        }

        class ViewHolder{
            private TextView tvName;
            private LinearLayout layoutSub;
            private CHScrollWXYJView layoutScroll;
        }
    }

    class MyClickLinstener implements View.OnClickListener {

        private int y_position;    // x 列数
        private int x_position;    // y 行数
        private boolean isCanEdit; // 是否可编辑
        private String content;

        public MyClickLinstener(int x_position,int y_position,boolean edit) {
            this.x_position = x_position;
            this.y_position = y_position;
            this.isCanEdit = edit;
        }

        public MyClickLinstener(int x_position,int y_position,boolean edit,String content) {
            this.x_position = x_position;
            this.y_position = y_position;
            this.isCanEdit = edit;
            this.content = content;
        }

        @Override
        public void onClick(View view) {
            mPositionX = x_position;
            mPositionY = y_position;
            if (isCanEdit){
                if ("0".equals(content) || "0.0".equals(content)){
                    content = "";
                }
                showEditDialogMsg(mBaseTitle[x_position],content);
            }
        }
    }

}
